package com.android.xunxian.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.xunxian.R;
import com.android.xunxian.adapter.DeviceAdpter;
import com.android.xunxian.entry.Device;
import com.android.xunxian.utils.UConstants;
import com.android.xunxian.utils.Util;
import com.android.xunxian.view.XListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 设备列表
 * Created by zouqh on 2016/7/3.
 */
public class DeviceActivity extends Activity implements View.OnClickListener, XListView.IXListViewListener {


    @InjectView(R.id.close)
    ImageView close;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @InjectView(R.id.ritgh_text)
    TextView ritghText;

    XListView listView;

    private List<Device> deviceList;
    private DeviceAdpter adpter;
    private int page = 1;
    private int pageSize = 12;
    private int allPage = 0;
    private String keyword = "";
    private String keyword1 = "";
    ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.device_activity);
        listView=(XListView)findViewById(R.id.listview);
        ButterKnife.inject(this);
        titleText.setText("设备列表");
        listView.setPullLoadEnable(true);// 向上滑动加载更多开启
        listView.setPullRefreshEnable(false);
        listView.setXListViewListener(this);
        listView.setFooterName("", false);
        deviceList=new ArrayList<>();
        adpter=new DeviceAdpter(this,deviceList);
        listView.setAdapter(adpter);
        getDate(keyword, keyword1);
        close.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(DeviceActivity.this,DeviceZBActivity.class);
                intent.putExtra("dn",deviceList.get(position-1).getDEVID());
                startActivity(intent);
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (page < allPage) {
                        page++;
                        getDate(keyword, keyword1);
                    } else {
                        listView.setFooterName("", false);
                    }
                    break;

            }

        }
    };

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.close:
                finish();
                break;
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        handler.sendEmptyMessage(1);
        onLoad();


    }

    private void onLoad() {
        listView.stopRefresh();
        listView.stopLoadMore();
        listView.setRefreshTime("刚刚");
    }


    //获取设备列表
    private void getDate(String devid, String devik) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.DEVICE_LIST);
        params.addBodyParameter("LKind", "CBJ");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("DEVID", devid);
        params.addBodyParameter("DEVKIND", devik);
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("Rows", pageSize + "");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        allPage = Integer.parseInt(object.getString("total"));
                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<Device>>() {
                            }.getType();
                            List<Device> list = gson.fromJson(object.getString("rows").toString(), lt);
//
                            if (list != null && list.size() > 0) {
//
                                deviceList.addAll(list);
                                adpter.notifyDataSetChanged();
                                if (page == allPage) {
                                    listView.setFooterName("", false);
                                } else if (page <= allPage) {
                                    listView.setFooterVisibility(true);
                                }

                            } else {
                                Toast.makeText(x.app(), "暂无设备！", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(x.app(), "暂无设备！", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }
}
